<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller {
	
	function __construct()
    {     	
    	parent::__construct();
    	if(get_cookie('id')) {
    		$this->session->set_userdata('id', get_cookie('id'));
			$this->session->set_userdata('avatar', get_cookie('avatar'));
			$this->session->set_userdata('name', get_cookie('name'));
    	}
		$this->load->model('category'); 
		$this->load->model('user'); 
		$this->load->model('adeal'); 
		$this->load->model('bill'); 
		$this->load->model('deal');
		$this->load->model('product'); 
		$this->load->model('receipt'); 
		$this->load->model('coupon'); 
		$this->load->model('banner'); 
		$this->load->helper('coupon');
		$this->load->helper('mail_body');
		$this->load->library('email');
		$this->load->library('session');

		$config['protocol'] = 'smtp';
		$config['charset'] = 'utf-8';
		$config['wordwrap'] = TRUE;
		$config['mailtype'] = 'html';
		$config['smtp_host'] = 'godeal.kz';
		$config['smtp_port'] = "25";
		$config['smtp_user'] = 'no-reply@godeal.kz';
		$config['smtp_pass'] = 'e5dd1998';
		$this->email->initialize($config);
    }
    
    public function index(){	
    	$data["categories"] = $this->category->getPageCategories();
		$data["session_avatar"] = $this->session->userdata('avatar');
		$data["session_id"] = $this->session->userdata('id');
		$data["session_name"] = $this->session->userdata('name');
		$data["adeals"] = $this->adeal->getFirstDeals();
		$this->load->view('home.php', $data);
	}

	public function all() {
		$data["categories"] = $this->category->getPageCategories();
		$data["session_avatar"] = $this->session->userdata('avatar');
		$data["session_id"] = $this->session->userdata('id');
		$data["session_name"] = $this->session->userdata('name');

		$data["page"] = 1;
		for ($i = 0; $i < func_num_args(); $i+=2) {
			$data[func_get_arg($i)] = func_get_arg($i + 1);
		}
		if(!isset($data["category"])) {
			$data["adeals"] = $this->adeal->getPageDeals($data["page"]);
		} else {
			$data["adeals"] = $this->adeal->getFilteredRows(array('category'=>$data['category']));
		}
		$this->load->view('all.php', $data);
	}

	public function signin() {
		$data["categories"] = $this->category->getPageCategories();
		if ($this->session->userdata('id')) {
			header('Location: /godeal/home/');
		} else {
			if ((func_num_args()>0) && (func_get_arg(0) == "error")) {
				$data["error"] = "Неверный email или пароль";
				$this->load->view('signin.php',$data);
			} else $this->load->view('signin.php', $data);
			
		}
	}

	public function login() {
		$this->load->model('user');
		if ($user = $this->user->userExist($_POST['email'],md5($_POST['pass']))) {
			$this->session->set_userdata('id', $user[0]->ID);
			$this->session->set_userdata('avatar', $user[0]->avatar);
			$this->session->set_userdata('name', $user[0]->name);

			if(isset($_POST["remember"])) {
				$cookie = array(
			    'name'   => 'id', 'value'  => $user[0]->ID,
			    'expire' => time()+60*60*24*365, 'domain' => '', 'path'   => '/', 
			    'prefix' => '', 'secure' => FALSE
				);
				set_cookie($cookie);
				$cookie = array(
			    'name'   => 'avatar', 'value'  => $user[0]->avatar,
			    'expire' => time()+60*60*24*365, 'domain' => '', 'path'   => '/',
			    'prefix' => '', 'secure' => FALSE
				);
				set_cookie($cookie);
				$cookie = array(
			    'name'   => 'name', 'value'  => $user[0]->name,
			    'expire' => time()+60*60*24*365, 'domain' => '', 'path'   => '/',
			    'prefix' => '', 'secure' => FALSE
				);
				set_cookie($cookie);
			}

			header('Location: /godeal/home/');
		} else {
			header('Location: /godeal/home/signin/error');
		}
	}

	public function signup(){
		if ((func_num_args()>0) && (func_get_arg(0) == "error")) {
			$data["error"] = "Ошибка";
			$this->load->view('signup.php',$data);
		} else if((func_num_args()>0) && (func_get_arg(0) == "error_pass")) {
			$data["error_pass"] = "error_pass";
			$this->load->view('signup.php',$data);
		} else $this->load->view('signup.php');
	}

    function register() {
    	$b = false;
    	if($_POST['pass'] != $_POST['pass_check'] || strlen($_POST['pass']) < 6) {
			header('Location: /godeal/home/signup/error_pass');
			$b = true;
		}
		
		if($this->user->mailExist($_POST['email'])) {
			header('Location: /godeal/home/signup/error');
			$b = true;
		}
        
		if(!$b) {
			$pass = md5($_POST['pass']);
	        $this->user->addUser($_POST['name'], 
	            $_POST['email']
	            ,$pass,$_POST['city']);

	        $this->email->from('no-reply@godeal.kz', 'GoDeal');
			$this->email->to($_POST['email']);

			$this->email->subject('Регистрация в GoDeal');
			$this->email->message(generateRegisteredMessage($_POST["name"]));	

			$this->email->send();
            
        	header('Location: /godeal');
        }
    }

    public function logout() {
		$this->session->sess_destroy();
		delete_cookie('id');
		delete_cookie('avatar');
		delete_cookie('name');

		header('Location: /godeal');
	}

	function feedback() {
		$data["categories"] = $this->category->getPageCategories();
		$data["session_id"] = $this->session->userdata('id');
		$data["session_name"] = $this->session->userdata('name');
		$data["session_avatar"] = $this->session->userdata('avatar');
		$data["adeals"] = $this->adeal->getFirstDeals();

		$this->load->view('feedback.php', $data);
	}

	public function cabinet() {
		$data["categories"] = $this->category->getPageCategories();
		$data["session_id"] = $this->session->userdata('id');
		$data["session_name"] = $this->session->userdata('name');
		$data["session_avatar"] = $this->session->userdata('avatar');
		$data["me"] = $this->user->getUserById($this->session->userdata('id'));
		$this->load->view('user.php', $data);
	}

	public function subscribe() {
		$this->user->subscribe($this->session->userdata('id'));
		$this->session->set_userdata(array('message' => 'Поздравляем! Теперь вы подписаны на нашу рассылку.'));
		header('Location: /godeal/home/cabinet');
	}

	public function unsubscribe() {
		$this->user->unsubscribe($this->session->userdata('id'));
		$this->session->set_userdata(array('message' => 'Вы отписались от нашей рассылки. Нам будет вас не хватать.'));
		header('Location: /godeal/home/cabinet');
        header('Location: /godeal/home/cabinet');
	}

	public function loadAva(){
		$config['upload_path'] = './images/';
		$config['allowed_types'] = 'jpg|jpeg|png|gif';
		$this->load->library('upload', $config);
		if ( ! $this->upload->do_upload()) {
			$error = array('error' => $this->upload->display_errors());
			$this->load->view('upload_error', $error);
		} else {
			$data = $this->upload->data();
			$img_url = "/images/".$data["file_name"];

			$config['image_library'] = 'gd2';
			$config['source_image'] = '.'.$img_url;
			$config['new_image'] = './images/userava/'.$data["file_name"];
			$config['maintain_ratio'] = FALSE;
			$config['width'] = 100;
			$config['height'] = 100;
			$this->load->library('image_lib', $config); 
			$this->image_lib->resize();

			unlink('.'.$img_url);

			$data = array(
    			'avatar' => '/images/userava/'.$data["file_name"]
    		 );
			$this->db->where('ID', $this->session->userdata('id'));
			$this->session->set_userdata('avatar', $data['avatar']);
			$this->db->set($data);
    		$this->db->update('users');
    		header('Location: /godeal/home/cabinet/');
		}
	}

	public function forgot() {
		$data["categories"] = $this->category->getPageCategories();
		if ($this->session->userdata('id')) {
			header('Location: /godeal/home/');
		} else {
			if ((func_num_args()>0) && (func_get_arg(0) == "error")) {
				$data["error"] = "E-mail не зарегистрирован в нашей базе";
				$this->load->view('forgot.php',$data);
			} else $this->load->view('forgot.php', $data);
		}
	}

	public function reset() {
		$email = strtolower($_POST['email']);

		$this->db->delete('forgot', array('email' => $email));

		$this->db->where('email', $email);
		$res = $this->db->get('users');
		if($res->num_rows() > 0) {
			$code = random_string('alnum', 32);
			$data = array(
	    		 'email' => $email,
	             'string' => $code
	    		 );
	    	$this->db->insert('forgot', $data); 

	    	$this->email->from('no-reply@godeal.kz', 'GoDeal');
			$this->email->to($email);
			$this->email->subject('GoDeal - Сброс пароля');
			$this->email->message(generateForgotMessage($code));	

			$this->email->send();
			
			header('Location: /godeal/home/instruct/'); 
		} else {
			header('Location: /godeal/home/forgot/error'); 
		}
	}

	public function instruct() {
		if ($this->session->userdata('id')) {
			header('Location: /godeal/home/');
		} else {
			$this->load->view('instruct.php');
		}
	}

	public function newpass() {
		$data["code"] = func_get_arg(0);
		if($this->session->userdata('reset_code')) {
			$data["code"] = $this->session->userdata('reset_code');
			$array_items = array('reset_code' => '');
			$this->session->unset_userdata($array_items);
		}
		
		$this->db->where('string', $data['code']);
		$res = $this->db->get('forgot');
		if($res->num_rows() > 0) {
			if ($this->session->userdata('id')) {
				header('Location: /godeal/home/');
			} else {
				if ((func_num_args()>0) && (func_get_arg(0) == "error")) {
					$data["error"] = "Пароли должны совпадать и состоять из более чем 6ти символов!";
					$this->load->view('newpass.php', $data);
				} else $this->load->view('newpass.php', $data);
			}
		} else {
			header('Location: /godeal/home/reseterror');
		}
	}

	public function resetpass() {
		if(strlen($_POST['pass']) < 6 || $_POST['pass'] != $_POST['check']) {
			$this->session->set_userdata(array('reset_code' => func_get_arg(0)));
			header('Location: /godeal/home/newpass/error');
		} else {
			$this->db->where('string', func_get_arg(0));
			$res = $this->db->get('forgot');
			$row = $res->result();

			$email = $row[0]->email;

			$this->db->where('email', $email);
			$this->db->set(array('pass' => md5($_POST['pass'])));
			$this->db->update('users');

			$this->db->where('email', $email);
			$this->db->delete('forgot');
			
			$this->session->set_userdata(array('message' => 'Пароль успешно изменен. Вы можете зайти с новыми данными.'));
			header('Location: /godeal/home/cabinet');
			header('Location: /godeal/home/');
		}
	}

	public function reseterror() {
		$this->load->view('reseterror.php');
	}

	public function changepass() {
		$this->db->where('id', $this->session->userdata('id'));
		$this->db->where('pass', md5($_POST['oldpass']));
		$res = $this->db->get('users');
		$rows = $res->result();
		if($res->num_rows() > 0) {
			if(strlen($_POST['pass']) < 6 || $_POST['pass'] != $_POST['pass_check']) {
				$this->session->set_userdata(array('message' => 'Не удалось поменять пароль. Длина нового пароля должна превышать 6 символов. 
					Пароль подтверждения должен совпадать.'));
				header('Location: /godeal/home/cabinet');
			} else {
				$this->db->where('id', $this->session->userdata('id'));
				$this->db->set('pass', md5($_POST['pass']));
				$this->db->update('users');
				$this->session->set_userdata(array('message' => 'Пароль успешно изменен.'));
				header('Location: /godeal/home/cabinet');
			}
		} else {
			$this->session->set_userdata(array('message' => 'Не удалось поменять пароль. Неверный пароль.'));
			header('Location: /godeal/home/cabinet');
		}
	}

	public function changeuser() {
		$this->db->where('id', $this->session->userdata('id'));
		$this->db->set('name', $_POST['name']);
		$this->db->set('email', $_POST['email']);

		$this->session->set_userdata('email', $_POST['email']);
		$this->session->set_userdata('name', $_POST['name']);

		if(isset($_POST['sex']))
			$this->db->set('sex', $_POST['sex']);
		$this->db->update('users');
		$this->session->set_userdata(array('message' => 'Ваша личная информация успешно обновлена.'));
		header('Location: /godeal/home/cabinet');
	}

	public function about() {
		$data["categories"] = $this->category->getPageCategories();
		$data["session_avatar"] = $this->session->userdata('avatar');
		$data["session_id"] = $this->session->userdata('id');
		$data["session_name"] = $this->session->userdata('name');

		$this->load->view('about.php', $data);
	}

	public function toclient() {
		$data["categories"] = $this->category->getPageCategories();
		$data["session_avatar"] = $this->session->userdata('avatar');
		$data["session_id"] = $this->session->userdata('id');
		$data["session_name"] = $this->session->userdata('name');

		$this->load->view('toclient.php', $data);
	}

	public function jobs() {
		$data["categories"] = $this->category->getPageCategories();
		$data["session_avatar"] = $this->session->userdata('avatar');
		$data["session_id"] = $this->session->userdata('id');
		$data["session_name"] = $this->session->userdata('name');

		$this->load->view('jobs.php', $data);
	}

	public function contact() {
		$data["categories"] = $this->category->getPageCategories();
		$data["session_avatar"] = $this->session->userdata('avatar');
		$data["session_id"] = $this->session->userdata('id');
		$data["session_name"] = $this->session->userdata('name');

		$this->load->view('contact.php', $data);
	}

	public function join() {
		$data["categories"] = $this->category->getPageCategories();
		$data["session_avatar"] = $this->session->userdata('avatar');
		$data["session_id"] = $this->session->userdata('id');
		$data["session_name"] = $this->session->userdata('name');

		$this->load->view('join.php', $data);
	}

	public function client() {
		$data["categories"] = $this->category->getPageCategories();
		$data["session_avatar"] = $this->session->userdata('avatar');
		$data["session_id"] = $this->session->userdata('id');
		$data["session_name"] = $this->session->userdata('name');

		$this->load->view('client.php', $data);
	}

	public function faq() {
		$data["categories"] = $this->category->getPageCategories();
		$data["session_avatar"] = $this->session->userdata('avatar');
		$data["session_id"] = $this->session->userdata('id');
		$data["session_name"] = $this->session->userdata('name');

		$this->load->view('faq.php', $data);
	}

	//---------------- Payment -----------------//

	public function newBill() {
		if ((func_num_args()>0) && (func_get_arg(0) == "product")) {
			$product = func_get_arg(1);
			$date = date("c", time()+21600);
			$date = substr($date,0,-6);
			$count = 1;
			if ((func_num_args()>2) && (func_get_arg(2) == "count"))
				$count = func_get_arg(3);
			if ($product!=0) {
				$cost = $this->product->getCostOfProduct($product); 
				$status = 'waiting';
			} else {
				$cost = 0;
				$status = 'account';
			}
			
			$bill = $this->bill->addBill($this->session->userdata('id'),$product,$date,$cost,$status, $count);

			$data["bill"] = $bill;
			$data["categories"] = $this->category->getPageCategories();
			$data["session_avatar"] = $this->session->userdata('avatar');
			$data["session_id"] = $this->session->userdata('id');
			$data["session_name"] = $this->session->userdata('name');
			$data["title"] = "Номер для оплаты счета";

			$this->load->view('kassa24s.php', $data);
		}
	}


	public function sendKass24Response($log, $code, $message) {
		
		$date = date("c", time()+21600);
		$date = substr($date,0,-6);
		
		$response = '<?xml version="1.0" encoding="utf-8"?>
						<response>
						     <code>'.$code.'</code>
						     <message>'.$message.'</message>
						     <date>'.$date.'</date>
						</response>';

		$log = $log.'//Response to Kass24 code='.$code.' message='.$message;
		log_message('info',$log);

		echo $response;
	}


	public function sendQiwiCheckResponse($log, $result, $comment, $osmp_txn_id) {
		
		$response = '<?xml version="1.0" encoding="utf-8"?>
						<response>
						     <osmp_txn_id>'.$osmp_txn_id.'</osmp_txn_id>
						     <result>'.$result.'</result>
						     <comment>'.$comment.'</comment>
						</response>';

		$log = $log.'//Response to Qiwi Check code='.$result.' message='.$comment;
		log_message('info',$log);

		echo $response;
	}


	public function sendQiwiPayResponse($log, $result, $comment, $osmp_txn_id, $prv_txn, $sum) {
		
		$response = '<?xml version="1.0" encoding="utf-8"?>
						<response>
						     <osmp_txn_id>'.$osmp_txn_id.'</osmp_txn_id>
						     <prv_txn>'.$prv_txn.'</prv_txn>
						     <sum>'.$sum.'</sum>
						     <result>'.$result.'</result>
						     <comment>'.$comment.'</comment>
						</response>';

		$log = $log.'//Response to Qiwi Pay code='.$result.' message='.$comment;
		log_message('info',$log);

		echo $response;
	}


	public function isCorrectDate($date) {
		return TRUE;	
	}

	public function isCorrectReceipt($receipt,$type) {
		$res = $this->receipt->getReceipt($receipt,$type);
		if (isset($res) && (count($res)>0) && isset($res[0])) {
			if ($res[0]->code==0) return FALSE; else return TRUE;
		} else return TRUE;	
	}

	
	public function qiwiGateway() {
		if(isset($_SERVER["HTTPS"]) && ($_SERVER['REMOTE_ADDR'] == '92.46.53.228' || 
										$_SERVER['REMOTE_ADDR'] == '212.154.215.82' || 
										$_SERVER['REMOTE_ADDR'] = '79.142.55.227')) {

			$log = 'Request from Qiwi';
			foreach($_GET as $key => $value)
				{
				   $log=$log.' '.$key.'='.$value;
				}
			$result = 1;
			$comment = 'Временная ошибка. Повторите запрос позже';
			
			if (isset($_GET['command'])) {
				$command = $_GET['command'];
				if ($command=='check') {
					$txn_id = '';
					if (isset($_GET['txn_id'])) {
						$txn_id = $_GET['txn_id'];
						$result=4;
						$comment = 'Неверный формат идентификатора абонента';
						if (isset($_GET['account'])) {
							$result=5;
							$comment = 'Идентификатор абонента не найден ';
							$account = $_GET['account'];
							$user = $this->user->getUserById($account);
							if (isset($user) && count($user)>0 && isset($user[0])) {
								$result = 0;
								$comment = 'Абонент найден';
							}
						}
					}
					$this->sendQiwiCheckResponse($log,$result,$comment,$txn_id);
				} else 
				if ($command=='pay') {
					$txn_id = '';
					$receipt_id = 0;
					$sum = 0.0;
					if (isset($_GET['txn_id'])) {
						$txn_id = $_GET['txn_id'];
						if ($this->isCorrectReceipt($txn_id,'qiwi')) {
							if (isset($_GET['txn_date'])) {
								$txn_date = $_GET['txn_date'];
								$result=4;
								$comment = 'Неверный формат идентификатора абонента';
								if (isset($_GET['account'])) {
									$result=5;
									$comment = 'Идентификатор абонента не найден ';
									$account = $_GET['account'];
									$user = $this->user->getUserById($account);
									if (isset($user) && count($user)>0 && isset($user[0])) {
										$result = 241;
										$comment = 'Сумма слишком мала';
										if (isset($_GET['sum']) && floatval($_GET['sum'])>0) {
											$sum = floatval($_GET['sum']);
											$result = 0;
											$comment = 'Платеж успешно принят'; 
											$this->db->trans_start();
											$this->user->addMoney($user[0]->ID,$sum);
											
											$receipt = $this->receipt->addReceipt($command, $user[0]->ID, $sum, $txn_id, $txn_date, $result, 'qiwi');
											$receipt_id = $receipt[0]->id;
											$this->db->trans_complete();

										}
									}
								}
							}
						} else {
							$receipt = $this->receipt->getReceipt($txn_id,'qiwi');
							$result = $receipt[0]->code;
							$comment = 'Платеж успешно принят';
							$receipt_id = $receipt[0]->id;
							$sum = $receipt[0]->amount;
						}
					}
					$this->sendQiwiPayResponse($log,$result,$comment,$txn_id,$receipt_id,$sum);
				}
			} 

			
		}
	}


	public function qiwiBillGateway() {
		if(isset($_SERVER["HTTPS"]) && ($_SERVER['REMOTE_ADDR'] == '92.46.53.228' || 
										$_SERVER['REMOTE_ADDR'] == '212.154.215.82' || 
										$_SERVER['REMOTE_ADDR'] = '79.142.55.227')) {

			$log = 'Request from Qiwi';
			foreach($_GET as $key => $value)
				{
				   $log=$log.' '.$key.'='.$value;
				}
			$result = 1;
			$comment = 'Временная ошибка. Повторите запрос позже';
			
			if (isset($_GET['command'])) {
				$command = $_GET['command'];
				if ($command=='check') {
					$txn_id = '';
					if (isset($_GET['txn_id'])) {
						$txn_id = $_GET['txn_id'];
						$result=4;
						$comment = 'Неверный формат идентификатора заказа';
						if (isset($_GET['account'])) {
							$result=5;
							$comment = 'Идентификатор заказа не найден ';
							$account = $_GET['account'];
							$bill = $this->bill->getBillById($account);
							if (isset($bill) && count($bill)>0 && isset($bill[0])) {
								$result = 0;
								$comment = 'Заказ найден '.(($bill[0]->cost)*($bill[0]->count));
							}
						}
					}
					$this->sendQiwiCheckResponse($log,$result,$comment,$txn_id);
				} else 
				if ($command=='pay') {
					$txn_id = '';
					$receipt_id = 0;
					$sum = 0.0;
					if (isset($_GET['txn_id'])) {
						$txn_id = $_GET['txn_id'];
						if ($this->isCorrectReceipt($txn_id,'qiwi')) {
							if (isset($_GET['txn_date'])) {
								$txn_date = $_GET['txn_date'];
								$result=4;
								$comment = 'Неверный формат заказа абонента';
								if (isset($_GET['account'])) {
									$result=5;
									$comment = 'Идентификатор заказа не найден ';
									$account = $_GET['account'];
									$bill = $this->bill->getBillById($account);
									if (isset($bill) && count($bill)>0 && isset($bill[0])) {
										$result = 241;
										$comment = 'Сумма слишком мала';
										if (isset($_GET['sum']) && floatval($_GET['sum'])>0) {
											$sum = floatval($_GET['sum']);
											$result = 0;
											$comment = 'Платеж успешно принят'; 
											$this->db->trans_start();
											
											$cost = $bill[0]->cost;
											$count = $bill[0]->count;
											do {
											$newcost = $cost - $sum;
											

											$remainder = 0;
										    if (abs($newcost)<0.0001) $newcost=0; 
										      elseif ($newcost<0) {
										      	$remainder = abs($newcost);
										        $newcost = 0;
										    }

										   if ($newcost == 0 && strcmp($bill[0]->status,'waiting')==0) {
										   		$product = $this->product->getProductById($bill[0]->product_id);
										   		$cost = $product[0]->cost;
										   		$count--;
										   		if ($count==0) {
										    		$this->bill->editBillStatus($bill[0]->id,'payed');
										    	} else {
										    		
										    		
										    		$this->bill->editBillCost($bill[0]->id,$cost);
										    		$sum = $remainder;
										    	}
										    	$this->bill->editBillCount($bill[0]->id,$count);
										    	
										    
										    	$deal = $this->deal->getDealById($product[0]->deal_id);
										    	
										    	$user = $this->user->getUserById($bill[0]->user_id);
										    	
										    	$date = date("c", time()+21600);
												$date = substr($date,0,-6);
												
										    	$this->coupon->generateCoupon($user[0]->ID,$product[0]->prod_id,$deal[0]->id,$deal[0]->partnerid,$product[0]->name,$user[0]->name,$product[0]->cost,$date,$product[0]->comission);
										    }
										} while ($remainder>0 && $count>0);
										    $this->user->addMoney($bill[0]->user_id,$remainder);
											$this->bill->editBillCost($bill[0]->id,$newcost);
											


											$receipt = $this->receipt->addReceipt($command, $bill[0]->user_id, $sum, $txn_id, $txn_date, $result, 'qiwi');
											$receipt_id = $receipt[0]->id;
											$this->db->trans_complete();

										}
									}
								}
							}
						} else {
							$receipt = $this->receipt->getReceipt($txn_id,'qiwi');
							$result = $receipt[0]->code;
							$comment = 'Платеж успешно принят';
							$receipt_id = $receipt[0]->id;
							$sum = $receipt[0]->amount;
						}
					}
					$this->sendQiwiPayResponse($log,$result,$comment,$txn_id,$receipt_id,$sum);
				}
			} 

			
		}
	}

	public function kass24Gateway() {
		if(isset($_SERVER["HTTPS"]) && ($_SERVER['REMOTE_ADDR'] == '88.204.242.62' || 
										$_SERVER['REMOTE_ADDR'] == '83.234.190.32' || 
										$_SERVER['REMOTE_ADDR'] = '89.218.238.146')) {

			$log = 'Request from Kass24';
			foreach($_GET as $key => $value)
				{
				   $log=$log.' '.$key.'='.$value;
				}
			$message = '';
			if (!isset($_GET['action'])) {
				$code = 1;
				$message = 'Неизвестный тип запроса';
			} else {
				$action = $_GET['action'];
				if ($action=='check') {
					$code = 2;
					$message = 'Заказ не найден';
					if (isset($_GET['number'])) {
						$number = $_GET['number'];
						$bill = $this->bill->getBillById($number);
						if (isset($bill) && (count($bill)>0) && isset($bill[0])) {
							$code = 0;
							$message = (($bill[0]->cost)*($bill[0]->count));
						}
					} 
				} else 
				if ($action=='payment') {
					$code = 2;
					$message = 'Заказ не найден';
					if (isset($_GET['number'])) {
						$number = $_GET['number'];
						$bill = $this->bill->getBillById($number);
						if (isset($bill) && (count($bill)>0) && isset($bill[0])) {
							$code = 3;
							$message = 'Неверная сумма платежа';
							if (isset($_GET['amount']) && floatval($_GET['amount'])>0) {
								$amount = floatval($_GET['amount']);
								$code = 4;
								$message = 'Неверное  значение номера платежа';
								if (isset($_GET['receipt'])) {
									$receipt = $_GET['receipt'];
									$code = 0;
									$message = 'Платеж уже принят';
									if ($this->isCorrectReceipt($_GET['receipt'],'kassa24')) {
									$code = 5;
									$message = 'Неверное значение даты';
										if (isset($_GET['date']) && $this->isCorrectDate($_GET['date'])) {
												$this->db->trans_start();
												$date = $_GET['date'];
												$cost = $bill[0]->cost;
												$count = $bill[0]->count;
												do {
												$newcost = $cost - $amount;
												
												$remainder = 0;
											    if (abs($newcost)<0.0001) $newcost=0; 
											      elseif ($newcost<0) {
											      	$remainder = abs($newcost);
											        $newcost = 0;
											    }
											    
												if ($newcost == 0 && strcmp($bill[0]->status,'waiting')==0) {
													$product = $this->product->getProductById($bill[0]->product_id);
													$cost = $product[0]->cost;
													$count--;
													if ($count == 0) {
														$this->bill->editBillStatus($bill[0]->id,'payed');
													} else {
														$this->bill->editBillCost($bill[0]->id,$cost);
											    		$amount = $remainder;
													}
											    	$this->bill->editBillCount($bill[0]->id,$count);
											    	
											    
											    	$deal = $this->deal->getDealById($product[0]->deal_id);
											    	
											    	$user = $this->user->getUserById($bill[0]->user_id);
											    	
											    	$date = date("c", time()+21600);
													$date = substr($date,0,-6);

											    	$this->coupon->generateCoupon($user[0]->ID,$product[0]->prod_id,$deal[0]->id,$deal[0]->partnerid,$product[0]->name,$user[0]->name,$product[0]->cost,$date,$product[0]->comission);
											    }
											} while ($remainder>0 && $count>0);
											    $this->user->addMoney($bill[0]->user_id,$remainder);
												$this->bill->editBillCost($bill[0]->id,$newcost);
												$code = 0;
												$message = 'Платеж принят';
												$res = $this->receipt->getReceipt($receipt,'kassa24');
												if (isset($res) && (count($res)>0) && isset($res[0])) {
													$this->receipt->editReceiptCode($receipt, $code,$date,'kassa24');
												} $this->receipt->addReceipt($action,$number,$amount,$receipt,$date,$code,'kassa24');

												$this->db->trans_complete();
										}
									}
								}
							}
						}
					} 


				} 
			}
			$this->sendKass24Response($log,$code,$message);
		}
	}

	function getIP() {
		//echo $_SERVER['REMOTE_ADDR'];
		echo random_string('num', 8);
	}

	function newCoupon() {
		$this->coupon->generateCoupon(1, 5, 4, 6, "Рыба", "Галымжан Абдугалимов", 100, date('Y-m-d'), 5);
	}
	
	function getCoupon() {
		$coupon = $this->coupon->getCouponById(func_get_arg(0));
		if($coupon[0]->user_id == $this->session->userdata('id') && $coupon[0]->status == 0) {
			$this->coupon->setPrinted(func_get_arg(0));
			$adeal = $this->adeal->getADealByDealId($coupon[0]->deal_id);
			$deal = $this->deal->getDealById($coupon[0]->deal_id);

			$data['couponid'] = $coupon[0]->code;
			$data['user_name'] = $coupon[0]->user_name;
			$data['product_name'] = $coupon[0]->prod_name;
			$data['cost'] = $coupon[0]->cost;
			$data['enddate'] = $coupon[0]->enddate;
			$data['specs'] = $adeal[0]->cond;
			$data['linkid'] = $adeal[0]->id;
			$data['img_url'] = $adeal[0]->img_url;
			$data['tel'] = $adeal[0]->tel;
			$data['address'] = $adeal[0]->address;
			$data['time'] = $adeal[0]->time;
			$data['type'] = $deal[0]->coupontype;
			$data['coords'] = $adeal[0]->coord;

			$this->load->view('coupon', $data);
		} else 
			echo "Купон не найден, либо не принадлежит вам или уже был использован";
	}

	function choosePayment() {
		$data["categories"] = $this->category->getPageCategories();
		$data["session_avatar"] = $this->session->userdata('avatar');
		$data["session_id"] = $this->session->userdata('id');
		$data["session_name"] = $this->session->userdata('name');
		$data['title'] = "Выберите способ оплаты";
		$data['me'] = $this->user->getUserById($this->session->userdata('id'));
		if(func_get_arg(0) == "product" && func_get_args() > 1)
			$data['product'] = func_get_arg(1);

		if($data['product'] != 0)
			$data["pr"] = $this->product->getProductById($data['product']);

		$this->load->view('choosePayment', $data);
	}

	function partners() {
		$data["categories"] = $this->category->getPageCategories();
		$data["session_avatar"] = $this->session->userdata('avatar');
		$data["session_id"] = $this->session->userdata('id');
		$data["session_name"] = $this->session->userdata('name');
		$data["banners"] = $this->banner->getBanners();
		$this->load->view('partners', $data);
	}

	function myBills() {
		$data["categories"] = $this->category->getPageCategories();
		$data["session_avatar"] = $this->session->userdata('avatar');
		$data["session_id"] = $this->session->userdata('id');
		$data["session_name"] = $this->session->userdata('name');
		$data["bills"] = $this->bill->getBillByUserId($this->session->userdata('id'));
		$data["title"] = "Мои счета";

		foreach ($data["bills"] as $bill) {
			$product[$bill->id] = $this->product->getProductById($bill->product_id);
		}
		$data["product"] = $product;
		$this->load->view('bills', $data);	
	}

	function deleteBill() {
		$this->bill->deleteUserBill(func_get_arg(0), $this->session->userdata('id'));
		header("Location: /godeal/home/myBills");
	}

	function accountBuy() {
		if(isset($_POST['product'])) {
			$product_id = $_POST['product'];

			$me = $this->user->getUserById($this->session->userdata('id'));
			$pr = $this->product->getProductById($product_id);
			$deal = $this->deal->getDealById($pr[0]->deal_id);
			if($pr[0]->cost < $me[0]->account) {
				$this->user->subtractMoney($this->session->userdata('id'), $pr[0]->cost);
			
				$data = $this->coupon->generateCoupon($this->session->userdata('id'), 
											  $pr[0]->prod_id, 
											  $pr[0]->deal_id, 
											  $deal[0]->partnerid, 
											  $pr[0]->name, 
											  $this->session->userdata('name'), 
											  $pr[0]->cost, 
											  $deal[0]->enddate,
										  	  $pr[0]->comission);

				header("Location: /godeal/home/getCoupon/" . $data);
			}
		}

		//header("Location: /godeal/home/myCoupons");
	}

	function myCoupons() {
		$data["categories"] = $this->category->getPageCategories();
		$data["session_avatar"] = $this->session->userdata('avatar');
		$data["session_id"] = $this->session->userdata('id');
		$data["session_name"] = $this->session->userdata('name');
		$data["coupons"] = $this->coupon->getCouponByUserId($this->session->userdata('id'));
		$data["title"] = "Мои счета";

		$this->load->view('myCoupons', $data);
	}

	function referer() {
		$user = $this->user->getUserById($this->session->userdata('id'));
		$user = $user[0];
		$referer = $this->user->getUserById($_POST['referer']);
		if(isset($referer[0])) {
			$referer = $referer[0];
			if($user->referer == 0 && $_POST['referer'] != $user->ID) {
				$this->user->addMoney($_POST['referer'], 100);
				$this->user->setReferer($this->session->userdata('id'), $_POST['referer']);
				$this->session->set_userdata(array('message' => 'Пользователю с введеным вами уникальным кодом зачислено 100тг.'));
			}
		}
		
		header('Location: /godeal/home/cabinet');
	}
}
